package imdbfolder.workers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.SwingWorker;

public abstract class MyWorker<T, V> extends SwingWorker<T, V> {

    private String title;

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    private List<ActionListener> finishedListeners = new ArrayList<ActionListener>();

    public void addFinishedListener(ActionListener listener) {
        finishedListeners.add(listener);
    }

    @Override
    protected final void done() {
        if (!isCancelled()) {
            onDone();

            for (ActionListener listener : finishedListeners) {
                listener.actionPerformed(new ActionEvent(this, 0, "done"));
            }
        }
    }

    private List<ActionListener> startedListeners = new ArrayList<ActionListener>();

    public void addstartedListener(ActionListener listener) {
        startedListeners.add(listener);
    }

    @Override
    protected final T doInBackground() throws Exception {
        if (!isCancelled()) {
            T result = onWork();

            for (ActionListener listener : startedListeners) {
                listener.actionPerformed(new ActionEvent(this, 0, "done"));
            }

            return result;
        }

        return null;
    }

    public void onDone() {

    }

    public abstract T onWork() throws Exception;
}
